/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainForm.java
 *
 * Created on 25.08.2011, 3:46:26
 */
package com.tsystems.school.simpleclient;

import java.awt.Color;
import java.awt.Component;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

/**
 *
 * @author 123
 */
public class MainForm extends javax.swing.JFrame {

    /** Creates new form MainForm */
    private String onlinePath = "\\images\\user_online.gif";
    private String offlinePath = "\\images\\user_offline.gif";
    private String messagePath = "C:\\images\\newmessage.gif";
    private String groupPath = "\\images\\group.gif";
    private ClientWorker cw;
    private MessageBox2 mb;
    


    public MainForm(ClientWorker cw) {
        
            initComponents();
            UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("---contacts---");
            Contact[] contacts = new Contact[]{new Contact("123"), new Contact("122")};
            for (int i = 0; i < contacts.length; i++) {

                root.add(new DefaultMutableTreeNode(contacts[i]));
            }
            contactTree.setModel(new DefaultTreeModel(root));
            contactTree.setCellRenderer(new IconNodeRenderer());
           //  cw = new ClientWorker(new Socket("localhost", 8080), this);
            this.cw = cw;
             //mb = new MessageBox2(cw);
             tree = contactTree;
             //new Thread(cw).start();        
    }

    class IconNodeRenderer extends DefaultTreeCellRenderer {

        public Component getTreeCellRendererComponent(JTree tree, Object value,
                boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {

            super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf,
                    row, hasFocus);
            Object current = ((DefaultMutableTreeNode) value).getUserObject();
            if (current instanceof Contact) {
                Contact contact = (Contact) current;
            boolean isOnline = contact.getStatus();
            boolean isNewMessage = contact.getMessageFlag();

            if (isOnline) {
                setIcon(new ImageIcon(onlinePath));
            } else {
                setIcon(new ImageIcon(offlinePath));
            }
            if (isNewMessage) {
                
                setIcon(new ImageIcon(messagePath));
            }
            } else {
                setIcon(new ImageIcon(groupPath));
            }
            return this;
        
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        contactTree = new javax.swing.JTree();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        contactTree.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                contactTreeMousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(contactTree);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 292, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(33, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void contactTreeMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_contactTreeMousePressed
       int selRow = contactTree.getRowForLocation(evt.getX(), evt.getY());
         TreePath selPath = contactTree.getPathForLocation(evt.getX(), evt.getY());
         if(selRow != -1) {
             if(evt.getClickCount() == 2) {
                 Object selected = ((DefaultMutableTreeNode) selPath.getLastPathComponent()).getUserObject();
                 if ( selected instanceof Contact) {
                     Contact cnt = (Contact)selected;
                     cnt.setMessageFlag(false);
//                        SimpleClient sc = new SimpleClient((Contact) selected);
                     if (mb == null) {
                       mb = new MessageBox2(cw);
                     }
                     if (mb.getTabMap().containsKey(cnt.getLogin())) {
                         mb.getTabPane().setSelectedComponent(mb.getTabMap().get(cnt.getLogin()));
                     }else {
                        mb.addTab(cnt);
                     }
                       mb.setVisible(true);

                 }
             }
         }
     
    }//GEN-LAST:event_contactTreeMousePressed

void addMessage(String sender, String string, Color clr, Date date) {
    System.out.println("trying..1");
    if (mb == null) {
        mb = new MessageBox2(cw);
    }
    MessagePane mpane = mb.getTabMap().get(sender);
        if (mpane!= null) {
            mpane.addMessagePane(sender, string, clr, date);
            repaint();
        } else {
            mb.addTab(new Contact(sender));
            addMessage(sender, string, clr, date);
        }
    }

    void writeHistory(String sender, String body, Date date) {
        if(mb == null)
            mb = new MessageBox2(cw);
        MessagePane mpane = mb.getTabMap().get(sender);
         if (mpane!= null) {
            mpane.writeToHistory(sender, body, date);
        } else {
            mb.addTab(new Contact(sender));
            mpane.writeToHistory(sender, body, date);
        }
    }
       
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MainForm().setVisible(true);
            }
        });
    }
    public static JTree getTree() {
        return tree;
    }
    private static JTree tree;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTree contactTree;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
